package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZIndustrialGroup;
import com.sec.etech.employeesync.mapper.OrgEmployeeZIndustrialGroupMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class IndustrialGroupConfigHandler implements ConfigTableHandler<OrgEmployeeZIndustrialGroup> {

    @Resource
    private OrgEmployeeZIndustrialGroupMapper industrialGroupMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZIndustrialGroup industrialGroup = getEntityByName(name);
        if (industrialGroup == null) {
            industrialGroup = new OrgEmployeeZIndustrialGroup();
            industrialGroup.setCode(generateNextCode());
            industrialGroup.setName(name);
            industrialGroup.setActive(1);
            insertEntity(industrialGroup);
            log.info("新增产业配置（二级）配置:name={}", name);
        }
        return industrialGroup.getIndustrialGroupId();
    }

    @Override
    public OrgEmployeeZIndustrialGroup getEntityByName(String name) {
        return industrialGroupMapper.selectOne(Wrappers.<OrgEmployeeZIndustrialGroup>lambdaQuery()
                .eq(OrgEmployeeZIndustrialGroup::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZIndustrialGroup politics = industrialGroupMapper.selectOne(Wrappers.<OrgEmployeeZIndustrialGroup>lambdaQuery()
                .orderByDesc(OrgEmployeeZIndustrialGroup::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZIndustrialGroup::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZIndustrialGroup entity) {
        industrialGroupMapper.insert(entity);
    }
}
